from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from goods.serializer import ProductSerializer
from goods.models import Product
from .models import Category
class childrenSerializer(ModelSerializer):
    products = serializers.SerializerMethodField()
    class Meta:
        model=Category
        fields=["id","name","icon","pid","products"]
    def get_products(self, obj):
        if obj.pid:
            queryset=Product.objects.filter(category_id=obj.id)[:4]
            return ProductSerializer(queryset, many=True).data
class CategorySerializer(ModelSerializer):
    children = serializers.SerializerMethodField()
    class Meta:
        model=Category
        fields=["id","name","icon","pid","children"]
    def get_children(self, obj):
        if not obj.pid:
            queryset=Category.objects.filter(pid=obj.id)
            print(queryset)
            return childrenSerializer(queryset, many=True).data




